// components/friendWaiting/friendWaiting.js
const app = getApp();
Page({
  data: {
    userInfo: {},
    battleInfo: {},
    battle_id: '',
    rightIn: ''
  },
  onLoad: function (options) {
    if (app.globalData.userInfo) {
      this.startData(options)
    } else {
      this.getInfo(options)
    }
  },
  startData(options) {
    if (options.hasOwnProperty('battle_id')) {
      this.setData({
        battle_id: options.battle_id,
        battleInfo: app.globalData.userInfo
      })
      app.globalData.acceptBattle = true
    } else {
      this.setData({
        battle_id: app.globalData.battleId,
        userInfo: app.globalData.userInfo
      })
    }
    this.updateData(options)
  },
  sendBattle: function () {
    let battle_id = this.data.battle_id
    let dataString = JSON.stringify({
      command: 'friend_battle',
      wx_id: app.globalData.wx_id,
      battle_id: battle_id
    })
    wx.sendSocketMessage({
      data: dataString
    })
  },
  acceptBattle: function () {
    let battle_id = this.data.battle_id
    let dataString = JSON.stringify({
      command: 'friend_battle_accept',
      wx_id: app.globalData.wx_id,
      battle_id: battle_id
    })
    wx.sendSocketMessage({
      data: dataString
    })
  },
  /**
   * 组件的方法列表
   */
  backIndex: function() {
    wx.navigateBack({
      url: '../index/index'
    });
  },
  updateData(options) {
    // 开启ws连接
    wx.connectSocket({
      url: 'wss://tydr.tihe-china.com/wss'
      // url: 'ws://120.27.224.239:8888'
    })
    // 监听ws的服务器返回
    wx.onSocketMessage((res) => {
      const resData = JSON.parse(res.data)
      if (resData.command === 'friend_battle_be_accept' || resData.command === 'friend_battle_opponent') {
        // 发起者或者挑战者
        if (options.hasOwnProperty('battle_id')) {
          this.setData({
            userInfo: resData.opponentInfo
          })
        } else {
          this.setData({
            battleInfo: resData.opponentInfo
          })
        }
        this.setData({
          rightIn: '0'
        })
        app.globalData.battleId = this.data.battle_id
        app.globalData.onlineBattleInfo = resData.opponentInfo
        wx.closeSocket()
        setTimeout(() => {
          wx.redirectTo({
            url: '../battle/battle'
          })
        }, 1500)
      } else if (resData.command === 'friend_battle_invalid') {
        // 失败
        wx.showToast({
          title: '此房间已失效',
          icon: 'none',
          complete: () => {
            setTimeout(() => {
              wx.redirectTo({
                url: '../index/index'
              })
            }, 1500)
          }
        })
      }
    })
    // 服务开启
    wx.onSocketOpen((res) => {
      if (options.hasOwnProperty('battle_id')) {
        this.acceptBattle()
      } else {
        this.sendBattle()
      }
    })
    // 服务异常
    wx.onSocketError(function (res) {
      // console.log('WebSocket连接打开失败，请检查！')
      wx.showToast({
        title: '服务异常',
        icon: 'none',
        complete: () => {
          setTimeout(() => {
            wx.redirectTo({
              url: '../index/index'
            })
          }, 1500)
        }
      })
    })
  },
  getInfo(options) {
    // 用户授权，获取个人信息
    wx.getUserInfo({
      lang: 'zh_CN',
      success: res => {
        this.getMyUserInfo(res.userInfo, options)
      },
      fail: res => {
        this.getUserInfoFail()
      }
    })
  },
  getMyUserInfo(userInfo, options) {
    wx.request({
      url: `${app.globalData.baseUrl}/user/${app.globalData.wx_id}`,
      // url: `${app.globalData.baseUrl}/user/test0001`,
      success: (res) => {
        if (Number(res.statusCode) === 200) {
          this.setData({
            userInfo: res.data
          })
          this.startData(options)
          app.globalData.userInfo = res.data
        } else if (Number(res.statusCode) === 404) {
          // 用户不存在，调注册的接口
          this.register(userInfo)
        }
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  register(userInfo) {
    let dataInfo = {
      wx_id: app.globalData.wx_id,
      wx_nickname: userInfo.nickName,
      wx_avatar: userInfo.avatarUrl,
      wx_address: userInfo.city
    }
    wx.request({
      url: `${app.globalData.baseUrl}/user`,
      method: 'POST',
      data: dataInfo,
      success: (res) => {
        this.getMyUserInfo(userInfo)
      },
      fail: (res) => {
      }
    })
  },
  getUserInfoFail () {
    wx.showModal({
      title: '警告',
      content: '若不授权微信登录，则无法使用太影达人；点击重新获取授权，则可重新使用；若点击不授权，后期还使用小程序，需在微信【发现】——【小程序】——删掉【太影达人】，重新搜索授权登录方可使用。',
      cancelText: '不授权',
      confirmText: '授权',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              this.getInfo()
            }
          })
        } else if (res.cancel) {
          wx.navigateBack()
        }
      }
    })
  }
})
